#include"UdpClient.hpp"

#include <iostream>
#include <cstring>
#include <string>
#include <cstdlib>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

int main(int argc,char* argv[])//argv[1]为服务器ip地址，argv[2]为端口号
{
    if(argc != 3)
    {
        std::cerr<<"Usage:./udp_client <server_ip> <server_port>"<<std::endl;
        exit(4);
    }

    std::string server_ip = argv[1];
    uint16_t server_port = std::atoi(argv[2]);

    //创建套接字
    int sock = socket(AF_INET,SOCK_DGRAM,0);
    if(sock < 0)
    {
        std::cerr << "socket error" << std::endl;
        exit(1);
    }

    struct sockaddr_in server_addr;
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(server_port);
    server_addr.sin_addr.s_addr = inet_addr(server_ip.c_str());

    //发送数据
    while(1)
    {
        std::cout<<"Enter:>";
        std::string msg;
        std::getline(std::cin,msg);
        sendto(sock,msg.c_str(),msg.size(),0,(struct sockaddr*)&server_addr,sizeof(server_addr));

        char buf[1024] = {0};
        ssize_t recv_size = recvfrom(sock,buf,sizeof(buf)-1,0,NULL,NULL);
        if(recv_size > 0)
        {
            std::cout<<"server echo:"<<buf<<std::endl;
        }
    }
    return 0;
}